//
//  CZDetailCommentModel.swift
//  GZWeibo007
//
//  Created by newuser on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class CZDetailCommentModel: NSObject {
    /// 用于显示正在加载数据cell
    var loading = false
    
    /// 评论的ID
    var id: Int = 0
    
    /// 评论创建时间
    var created_at: String?
    
    /// 评论作者的用户信息字段
    var user: CZUser?
    
    /// 内容
    var text: String?
    
    
    init(loading: Bool) {
        self.loading = loading
        super.init()
    }
    //字典转模型
    init(dict:[String: AnyObject])
    {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            
            if let dict = value as? [String: AnyObject] {
               user = CZUser(dict: dict)
            }
            return
        }
         super.setValue(value, forKey: key)
    }
    
    //实现没有属性的方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}

     override var description: String {
        let properties = ["id", "created_at", "user"]
        return "\n\t:评论模型: \(dictionaryWithValuesForKeys(properties))"
    }
    
    // MARK: - 获取数据
    ///  模型获取数据
  class func loadComment(statusId: Int, since_id: Int, max_id: Int, finished:(comments: [CZDetailCommentModel]?, total_number: Int?, previous_cursor: Int?, next_cursor: Int?, error: NSError?) -> ()) {
        //调用工具栏方法
    CZNetworkTool.sharedInstance.loadComment(statusId, since_id: since_id, max_id: max_id) { (result, error) -> () in
        //如果有错误
        if error != nil {
            print("加载评论失败:\(error)")
            finished(comments: nil, total_number: nil, previous_cursor: nil, next_cursor: nil, error: error)
            return
        }
        print("result:\(result)")
        //总数量
        let total_number = result?["total_number"] as? Int
        //上一页
        let previous_cursor = result?["previous_cursor"] as? Int
        //下一页
        let next_cursor = result?["next_cursor"] as? Int
        
        //定义数组
        var comments = [CZDetailCommentModel]()
        
        if let array = result?["comments"] as? [[String: AnyObject]] {
           //遍历
            for dict in array {
                let comment = CZDetailCommentModel(dict: dict)
                comments.append(comment)
            }
        
            finished(comments: comments, total_number: total_number, previous_cursor: previous_cursor, next_cursor: next_cursor, error: nil)
        }else {
            
           finished(comments: nil, total_number: total_number, previous_cursor: previous_cursor, next_cursor: next_cursor, error: nil)
        }
        
     }
    
    }
    
}
